<?php

namespace Home\Controller;

use Common\Controller\CommonController;

class ArticleController extends CommonController {
	protected $article = null;

	public function _initialize() {
		$this->article = D('Article');
	}

	//判断请求来源并写入日志
	function judgeSpilider() {
		$flag = false;
		$tmp = $_SERVER['HTTP_USER_AGENT'];
		if (strpos($tmp, 'Googlebot') !== false) {
			$flag = true;
		} else if (strpos($tmp, 'Baiduspider') > 0) {
			$flag = true;
		} else if (strpos($tmp, 'Yahoo! Slurp') !== false) {
			$flag = true;
		} else if (strpos($tmp, 'msnbot') !== false) {
			$flag = true;
		} else if (strpos($tmp, 'Sosospider') !== false) {
			$flag = true;
		} else if (strpos($tmp, 'YodaoBot') !== false || strpos($tmp, 'OutfoxBot') !== false) {
			$flag = true;
		} else if (strpos($tmp, 'Sogou web spider') !== false || strpos($tmp, 'Sogou Orion spider') !== false) {
			$flag = true;
		} else if (strpos($tmp, 'fast-webcrawler') !== false) {
			$flag = true;
		} else if (strpos($tmp, 'Gaisbot') !== false) {
			$flag = true;
		} else if (strpos($tmp, 'ia_archiver') !== false) {
			$flag = true;
		} else if (strpos($tmp, 'altavista') !== false) {
			$flag = true;
		} else if (strpos($tmp, 'lycos_spider') !== false) {
			$flag = true;
		} else if (strpos($tmp, 'Inktomi slurp') !== false) {
			$flag = true;
		}
		$title = "默认标题";
		//写入日志
		if ($flag) {
			file_put_contents("spilider.txt", $_SERVER['HTTP_USER_AGENT'] . "- " . date("Y-m-d H:i:s") . "\n");
			$title = "python 是最好的语言";
		}
		$this->assign("title", $title);
		$this->display("add");
	}
	//列表
	public function lists() {
		$opt = [];
		$page = I('page', 1);
		$pageSize = 20;
		$data = $this->article->getAllByLimit($opt, $page, $pageSize);

		$pageData['pageInfo'] = pagination($page, $data['count'], $pageSize);
		$this->assign('data', $data);
		$this->assign('pageData', $pageData);
		$this->display();
	}

	//前端分页
	public function callback_lists() {
		$opt = [];
		$page = I('page', 1);
		$pageSize = 20;
		$data = $this->article->getAllByLimit($opt, $page, $pageSize);
		$this->ajaxReturn(array('data' => $data, 'msg' => '成功！', 'error_code' => 0));
	}

	//新增
	public function add() {
		$this->display();
	}

	public function add_callback() {
		if (!$this->article->create()) {
			$this->ajaxReturn(array('msg' => $this->article->getError(), 'error_code' => 1));
		}
		$this->article->content = $_POST['content'];
		$this->article->add();
		$this->ajaxReturn(array('msg' => '新增成功！', 'error_code' => 0));
	}

	public function edit() {
		$id = I('id');
		$row = $this->article->where("id={$id}")->find();
		$this->assign('row', $row);
		$this->display();
	}

	public function edit_callback() {
		$id = I('id');
		if (!$this->article->create()) {
			$this->ajaxReturn(array('msg' => $this->article->getError(), 'error_code' => 1));
		}

		$this->article->where("id={$id}")->save();
		$this->ajaxReturn(array('msg' => '修改成功！', 'error_code' => 0));
	}

	public function del_callback() {
		$id = I('id');
		$this->article->where("id={$id}")->delete();
		$this->ajaxReturn(array('msg' => '删除成功！', 'error_code' => 0));
	}

	public function uploadImage() {
		$upload = new \Think\Upload(); // 实例化上传类
		$upload->maxSize = 3145728; // 设置附件上传大小
		$upload->exts = array('jpg', 'gif', 'png', 'jpeg'); // 设置附件上传类型
		$upload->rootPath = './Uploads/'; // 设置附件上传根目录
		$upload->savePath = ''; // 设置附件上传（子）目录
		// 上传文件
		$info = $upload->upload();
		if (!$info) {
			$this->ajaxReturn(array('code' => 1, 'msg' => $upload->getError()));
		} else {
			foreach ($info as $k => $v) {
				$real_path = $v['savepath'] . $v['savename'];
			}
			$this->ajaxReturn(array('code' => 0, 'msg' => '成功', 'data' => array('src' => 'http://www.layui.test/Uploads/' . $real_path, 'title' => '土拨鼠')));
		}
	}

	//图片懒加载
	public function layimg() {
		$opt = [];
		$page = I('page', 1);
		$pageSize = 6;
		$data = $this->article->getAllByLimit($opt, $page, $pageSize);
		$this->assign('data', $data['data']);
		$this->display('img');
	}

	public function layimg_callback() {
		$opt = [];
		$page = I('page', 1);
		$pageSize = 2;
		$data = $this->article->getAllByLimit($opt, $page, $pageSize);
		$this->ajaxReturn(array('error_code' => 0, 'data' => $data['data'], 'pages' => 5));
	}

	public function test() {
		$row = $this->article->limit(1)->order('id desc')->select();
		$row['state'] = 2;
		$row['job_uid'] = 61;
//        var_dump($row);die;
		if (!empty($row['job_uid']) && $row['state'] == 2 && $row['is_check'] != 1) {
			echo 'is_check null';
			return;
		}
		echo 'is_check null';
	}

	/**
	 * 更新文章触发
	 * 更改 is_check  和  check_time
	 */
	public function UpdateCheckAndTime($model, $id) {
		$row = $model->where("id={$id}")->find();
		if (!empty($row)) {
			if (!empty($row['job_uid']) && $row['state'] == 2 && $row['is_check'] != 1) {
				$data = array('check_time' => date('Y-m-d H:i:s'), 'is_check' => 1);
				$model->where("id={$row['id']}")->save($data);
			}
		}

	}

	public function getList() {

		$data = $this->article->select();
		$image = new \Think\Image();

		$result = [];
		foreach ($data as $k => $v) {
			$parseArr = parse_url($v['pic']);
			$pic = $parseArr['path'];
			if (!$pic) {
				continue;
			}
			$image->open(ROOT_DIR . $pic);
			$width = $image->width(); // 返回图片的宽度
			$height = $image->height(); // 返回图片的高度

			$item = [];
			$item['id'] = $v['id'];
			$item['title'] = ($k + 1) . ';w-' . $width . ';h-' . $height;
			$result[] = $item;
		}
		if ($result[0]) {
			$id = $this->batch_update("Article", $result, $field = 'id');
			if (!$id) {
				echo "ERROR!";
				return;
			}
		}
		echo "SUCCESS!";

	}

	function batch_update($table_name = '', $data = array(), $field = '') {

		if (!$table_name || !$data || !$field) {

			return false;

		} else {

			$sql = 'UPDATE ' . $table_name;

		}

		$con = array();

		$con_sql = array();

		$fields = array();

		foreach ($data as $key => $value) {

			$x = 0;

			foreach ($value as $k => $v) {

				if ($k != $field && !$con[$x] && $x == 0) {

					$con[$x] = " set {$k} = (CASE {$field} ";

				} elseif ($k != $field && !$con[$x] && $x > 0) {

					$con[$x] = " {$k} = (CASE {$field} ";

				}

				if ($k != $field) {

					$temp = $value[$field];

					$con_sql[$x] .= " WHEN '{$temp}' THEN '{$v}' ";

					$x++;

				}

			}

			$temp = $value[$field];

			if (!in_array($temp, $fields)) {

				$fields[] = $temp;

			}

		}

		$num = count($con) - 1;

		foreach ($con as $key => $value) {

			foreach ($con_sql as $k => $v) {

				if ($k == $key && $key < $num) {

					$sql .= $value . $v . ' end),';

				} elseif ($k == $key && $key == $num) {

					$sql .= $value . $v . ' end)';

				}

			}

		}

		$str = implode(',', $fields);

		$sql .= " where {$field} in({$str})";

		$res = M($table_name)->execute($sql);

		return $res;

	}

	public function attrJob() {
		$model = M("test");
		$model->where('id=4')->setInc('num', 1); // 点赞+1
	}

}